package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;


    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private Executor executor;


    @Autowired
    private RedissonClient redissonClient;


    /**
     * 获取详情页所需的数据
     *
     * @param albumId
     * @return {albumInfo:{专辑信息},baseCategoryView:{分类对象},albumStatVo:{专辑统计信息},announcer:{主播信息}}
     */
    @Override
    public Map<String, Object> getItemData(Long albumId) {
        //0.TODO 判断用户访问专辑是否存在
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        if(!bloomFilter.contains(albumId)){
            throw new RuntimeException("专辑不存在");
        }
        log.info("getItemData方法线程信息：{}", Thread.currentThread().getId());
        //1.准备Map封装返回数据 HashMap不是线程安全的，多线程并发写HashMap会导致数据丢失。采用线程安全ConcurrentHashMap
        Map<String, Object> map = new ConcurrentHashMap<>();

        //2.远程调用专辑服务，根据专辑ID查询专辑信息，封装专辑信息
        CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            log.info("getItemData内部开启子线程查询专辑信息：{}", Thread.currentThread().getId());
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑{}不存在", albumId);
            map.put("albumInfo", albumInfo);
            return albumInfo;
        }, executor);

        //3.远程调用专辑服务，根据三级分类ID查询分类信息，封装分类信息
        CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            log.info("getItemData内部开启子线程查询分类信息：{}", Thread.currentThread().getId());
            Long category3Id = albumInfo.getCategory3Id();
            BaseCategoryView baseCategoryView = albumFeignClient.getCategoryView(category3Id).getData();
            Assert.notNull(baseCategoryView, "分类{}不存在", category3Id);
            map.put("baseCategoryView", baseCategoryView);
        }, executor);

        //4.远程调用用户服务，根据主播ID查询主播信息，封装主播信息
        CompletableFuture<Void> announcerCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> {
            Long userId = albumInfo.getUserId();
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
            Assert.notNull(userInfoVo, "主播{}不存在", userId);
            map.put("announcer", userInfoVo);
        }, executor);

        //5.远程调用专辑服务，根据辑ID查询统计信息，封装统计信息
        CompletableFuture<Void> albumStatVoCompletableFuture = CompletableFuture.runAsync(() -> {
            AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData();
            Assert.notNull(albumStatVo, "专辑{}不存在", albumId);
            map.put("albumStatVo", albumStatVo);
        }, executor);

        //6.组合所有异步任务
        CompletableFuture.allOf(
                albumInfoCompletableFuture,
                albumStatVoCompletableFuture,
                baseCategoryViewCompletableFuture,
                announcerCompletableFuture
        ).join();
        return map;
    }
}
